//
//  HomeViewController.swift
//  FastDevelop
//
//  Created by IOS1 on 2025/6/26.
//

import UIKit

private let headerID    = "DateHeaderView"
class HomeViewController: BaseViewController, UITextFieldDelegate {

    private var dataSource = [DailyLog]()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private func setupUI(){
        
        view.addSubviews([
            titleLabel,
            searchTextF,
            emptyV,
            emptyLabel,
            tableView,
            addButton
        ])
        
        titleLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalToSuperview().offset(CGFloat.statusHeight)
            make.height.equalTo(44)
        }
        searchTextF.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.trailing.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(CGFloat.navi_height)
            make.height.equalTo(47)
        }
        addButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-(CGFloat.tabBar_height + 33))
            make.width.height.equalTo(68)
        }
        emptyV.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(searchTextF.snp.bottom).offset(123)
            make.width.equalTo(153)
            make.height.equalTo(158)
        }
        emptyLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(emptyV.snp.bottom).offset(80)
        }
        tableView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(searchTextF.snp.bottom).offset(20)
            make.bottom.equalToSuperview().offset(-CGFloat.tabBar_height)
        }
        
        loadLogsData()
    }
    
    private func loadLogsData(){
        
        Task{            
            let res = await network.request(.loginLog, type: LogsModel.self)
            if let md = res.model, res.isSuccess{
                print("===\(md.item1)")
                print("===\(md.item2)")
            }
        }
    }
    
    private func loadData(){
        
        self.dataSource = self.loadDailyLogs(forKey: "dailyLogs")
        if dataSource.count == 0 {
            
            emptyV.isHidden = false
            emptyLabel.isHidden = false
            tableView.isHidden = true
        }else{
            
            emptyV.isHidden = true
            emptyLabel.isHidden = true
            tableView.isHidden = false
            tableView.reloadData()
        }
    }
    
    // 点击键盘上的 Search 按钮时触发
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == searchTextF {
            search(keyword: textField.text ?? "")
            textField.resignFirstResponder()  // 收起键盘
            return true
        }
        return false
    }

    private func search(keyword: String) {

        let result = searchDailyLogs(containing: keyword, forKey: "dailyLogs")
        self.dataSource = result
        if dataSource.count == 0 {
            
            emptyV.isHidden = false
            emptyLabel.isHidden = false
            tableView.isHidden = true
        }else{
            
            emptyV.isHidden = true
            emptyLabel.isHidden = true
            tableView.isHidden = false
            tableView.reloadData()
        }
    }
    
    @objc private func clickAddButton(){
        
        let today = Date()
        let writeDate = today.formattedCalendarDate()
        let addVC = AddNoteViewController()
        addVC.writeDate =  writeDate
        self.navigationController?.pushViewController(addVC, animated: true)
    }

    private lazy var titleLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.font = UIFont.boldSystemFont(ofSize: 18)
        v.text = "ZentriNot"
        v.textAlignment = .center
        return v
    }()
    private lazy var searchTextF: UITextField = {
        let v = UITextField()
        v.placeholder = "Notizen durchsuchen"
        v.textColor = .black
        v.font = UIFont.boldSystemFont(ofSize: 16)
        v.backgroundColor = UIColor(hexString: "#EEF2F5")
        v.returnKeyType = .search
        v.delegate = self
        let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 51, height: 47))
        let searchV = UIImageView(image: UIImage(named: "home_search"))
        searchV.frame = CGRect(x: 12, y: 12, width: 24, height: 24)
        leftV.addSubview(searchV)
        v.leftView = leftV
        v.leftViewMode = .always
        v.layer.cornerRadius = 8
        v.layer.masksToBounds = true
        return v
    }()
    private lazy var addButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage(UIImage(named: "home_add"), for: .normal)
        v.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        return v
    }()
    private lazy var emptyV: UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleAspectFill
        v.image = UIImage(named: "home_empty")
        v.isHidden = true
        return v
    }()
    private lazy var emptyLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.font = UIFont.boldSystemFont(ofSize: 24)
        v.text = "Ich habe heute noch keine\nNotizen geschrieben"
        v.textAlignment = .center
        v.numberOfLines = 2
        v.isHidden = true
        return v
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(NoteListCell.self, forCellReuseIdentifier: "NoteListCell")
        tableView.register(DateHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 200.0
        tableView.isHidden = true
        return tableView
    }()
}

extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataSource[section].data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.cell(NoteListCell.self, indexPath: indexPath)
        cell.model = dataSource[indexPath.section].data[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! DateHeaderView
        header.model = dataSource[section]
        return header
        
    }
}
